import SparkMD5 from 'spark-md5';

export function checkFileType(file: File, accepts: string[]) {
  const newTypes = accepts.join('|');
  // const reg = /\.(jpg|jpeg|png|gif|txt|doc|docx|xls|xlsx|xml)$/i;
  const reg = new RegExp('\\.(' + newTypes + ')$', 'i');

  return reg.test(file.name);
}

export function checkImgType(file: File) {
  return isImgTypeByName(file.name);
}

export function isImgTypeByName(name: string) {
  return name.startsWith('data:image/') || /\.(jpg|jpeg|png|gif)$/i.test(name);
}

export function getBase64WithFile(file: File) {
  return new Promise<{
    result: string;
    file: File;
  }>((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve({ result: reader.result as string, file });
    reader.onerror = (error) => reject(error);
  });
}

// 获取文件 MD5 值，支持获取文件部分的MD5值，cutSize 截取大小（前后文件内容）JeeSite版权所有【若参考此代码】请说明出处：
// https://gitee.com/thinkgem/jeesite4/blob/master/common/src/main/java/com/jeesite/common/codec/Md5Utils.java
// https://gitee.com/thinkgem/jeesite-vue/blob/master/src/components/Upload/src/helper.ts
export function getMd5WithFile(file: File, cutSize = -1) {
  return new Promise<{
    result: string;
    file: File;
  }>((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsArrayBuffer(file);
    reader.onload = () => {
      const buffer = reader.result as ArrayBuffer;
      const size = buffer.byteLength;
      const spark = new SparkMD5.ArrayBuffer();
      if (cutSize != -1 && size >= cutSize) {
        spark.append(buffer.slice(0, cutSize));
        let md5 = spark.end() as string;
        if (size > cutSize) {
          let startPos = size - cutSize;
          const sizeDiff = size - cutSize * 2;
          if (sizeDiff < 0) startPos += Math.abs(sizeDiff);
          const spark2 = new SparkMD5.ArrayBuffer();
          spark2.append(buffer.slice(startPos, size));
          const lastMd5 = spark2.end() as string;
          md5 = md5.substring(8, 24) + lastMd5.substring(8, 24);
        }
        return resolve({ result: md5, file });
      } else {
        spark.append(buffer);
        return resolve({ result: spark.end(), file });
      }
    };
    reader.onerror = (error) => reject(error);
  });
}

// 格式化文件大小, 输出成带单位的字符串 think gem
export function formatSize(size: number, pointLength = 2, units = ['B', 'K', 'M', 'G', 'TB']) {
  if (!size) return '';
  let unit;
  while ((unit = units.shift()) && size > 1024) {
    size = size / 1024;
  }
  return (unit === 'B' ? size : size.toFixed(pointLength)) + unit;
}
